<?php	
	include("mysql_connect.php");
	//include("error/upload.php");

	/*$xmlstring = '
	<UserPhoto UserName="rafale@thetigerparty.com" BoardID="23">
		<Media ID="" BeMediaID="" MediaType="Camera" Author="rafale@thetigerparty.com" lastUpdate="2012-09-03 10:40 AM">
			<Text ID="" Title="Photo Saved" Description="happy EveryDay"/>
			<Image ID="" Type="JPG" FileName="SuperMan.jpg" Description=""/>
		</Media>
	</UserPhoto>';*/
	
	if ($_FILES["file"]["error"] > 0)
	{
		switch ( $_FILES [ $field ][ 'error' ])
		{
			case 1:	// UPLOAD_ERR_INI_SIZE  
				$strError = "The file is too large (server).";  
				break ;  
			case 2:	// UPLOAD_ERR_FORM_SIZE  
				$strError = "The file is too large (form).";  
				break ;  
			case 3: // UPLOAD_ERR_PARTIAL  
				$strError = "The file was only partially uploaded.";  
				break ;  
			case 4: // UPLOAD_ERR_NO_FILE  
				$strError = "No file was uploaded.";  
				break ;  
			case 5: // missing tmp folder
				$strError = "The servers temporary folder is missing.";  
				break ;  
			case 6:	// UPLOAD_ERR_NO_TMP_DIR  
				$strError = "Failed to write to the temporary folder.";  
				break ;  
			case 7: // UPLOAD_ERR_CANT_WRITE  
				$strError = "Failed to write file to disk.";  
				break ;  
			case 8: // UPLOAD_ERR_EXTENSION
				$strError = "File upload stopped by extension.";  
				break ;
			default:
				$strError = "Unknow Error";
		}
		error_log( "[".date("Y-m-d H:i:s")."] : ".$strError."\n", 3, "upload-errors.log" );  
			
		echo '<Error Message="'.$_FILES["file"]["error"].'" Domain="UserUpload" />';
		//saveError("UserUpload", NULL, date("Y-m-d H:i:s"), $_FILES["file"]["error"]);
		exit;
	}

	//$xml = simplexml_load_string($xmlstring);

	//$xml = simplexml_load_file('php://input');
	$xml = simplexml_load_string($_POST['xml']);
//*/


	foreach( $xml->attributes( ) as $attr)
	{
		$User[] = (string)$attr;
	}
	
	foreach( $xml->children( ) as $Media)
	{
		foreach( $Media->attributes( ) as $attr)
		{
			$MediaData[] = (string)$attr;
		}
		
		foreach( $Media->children( ) as $Item)
		{
			switch ($Item->getName())
			{
				case "Text":
					foreach( $Item->attributes( ) as $attr)
					{
						$Text[] = (string)$attr;
					}
					break;
				case "Image":
					foreach( $Item->attributes( ) as $attr)
					{
						$Image[] = (string)$attr;
					}
					break;
			}
		}
	}

	//include("mysql_connect.php");
// Check User & Get User ID
	$strSqlCommand = 'SELECT idUSER FROM user WHERE Email = "'.$User[0].'"';
	if (! $result = mysql_query($strSqlCommand))
 	{
	 	echo '<Error Message="'.mysql_error().'" Domain="UserUpload" />';
				error_log( "[".date("Y-m-d H:i:s")."] : ".mysql_error()."\n", 3, "upload-errors.log" );  
				error_log( $strSqlCommand."\n", 3, "upload-errors.log" ); 
		//saveError("UserUpload", NULL, date("Y-m-d H:i:s"), mysql_error()); 

		exit;
 	}
	if( mysql_num_rows($result) > 0)
	{
		$GetUser = @mysql_fetch_array($result);
		$idUSER = $GetUser['idUSER'];
	// Add Media To SQL
			//Create Media in database
			//$strSqlCommand = "INSERT INTO media (MEDIA_TYPE_idMEDIA_TYPE, ModifyTime) 
			//				VALUES ('7',FROM_UNIXTIME(".strtotime($MediaData[4])."))";
			$strSqlCommand = "INSERT INTO media (MEDIA_TYPE_idMEDIA_TYPE, ModifyTime, USER_idUSER) 
							VALUES ('7','".date("Y-m-d H:i:s")."', '".$idUSER."')";
			
			if (!mysql_query($strSqlCommand))
 			{
	 			echo '<Error Message="'.mysql_error().'" Domain="UserUpload" />';
				error_log( "[".date("Y-m-d H:i:s")."] : ".mysql_error()."\n", 3, "upload-errors.log" );  
				error_log( $strSqlCommand."\n", 3, "upload-errors.log" );  
				//saveError("UserUpload", NULL, date("Y-m-d H:i:s"), mysql_error()); 
				exit;
 			}

		// Get New Media ID
		$nMediaID= mysql_insert_id();
	// Add spot_user_sb_m
		$BoardID = $User[1];
		$strSqlCommand = "INSERT INTO spot_user_sb_m ( MEDIA_idMEDIA, STORYBOARD_idSTORYBOARD, USER_idUSER ) 
							VALUES ( $nMediaID, $BoardID, $idUSER)";

		if (!mysql_query($strSqlCommand))
 		{
	 		echo '<Error Message="'.mysql_error().'" Domain="UserUpload" />';
				error_log( "[".date("Y-m-d H:i:s")."] : ".mysql_error()."\n", 3, "upload-errors.log" );  
				error_log( $strSqlCommand."\n", 3, "upload-errors.log" );  
			//saveError("UserUpload", NULL, date("Y-m-d H:i:s"), mysql_error()); 
			exit;
 		}
	// Add Text To SQL
		$strSqlCommand = "INSERT INTO text (Title, Description, MEDIA_idMEDIA) 
							VALUES (\"$Text[1]\",\"$Text[2]\",$nMediaID)";

		if (!mysql_query($strSqlCommand))
 		{
	 		echo '<Error Message="'.mysql_error().'" Domain="UserUpload" />';
				error_log( "[".date("Y-m-d H:i:s")."] : ".mysql_error()."\n", 3, "upload-errors.log" );  
				error_log( $strSqlCommand."\n", 3, "upload-errors.log" );  
			//saveError("UserUpload", NULL, date("Y-m-d H:i:s"), mysql_error()); 
			exit;
 		}	
		// Get New Text ID
		$nTextID = mysql_insert_id();
	// Add Image To SQL
		$strSqlCommand = "INSERT INTO image (Type, Width, Height, FileName, MEDIA_idMEDIA) 
							VALUES (\"$Image[1]\",\"$Image[2]\",\"$Image[3]\",\"$Image[4]\",$nMediaID)";
		if (!mysql_query($strSqlCommand))
 		{
	 		echo '<Error Message="'.mysql_error().'" Domain="UserUpload" />';
				error_log( "[".date("Y-m-d H:i:s")."] : ".mysql_error()."\n", 3, "upload-errors.log" );  
				error_log( $strSqlCommand."\n", 3, "upload-errors.log" );  
			//saveError("UserUpload", NULL, date("Y-m-d H:i:s"), mysql_error()); 
			exit;
 		}
		// Get New Image ID
		$nImageID = mysql_insert_id();
	}// End of Check User & Get User ID
// No User
	else
	{
		echo '<Error Message="User Account was not found" Domain="UserUpload" />';
				error_log( "[".date("Y-m-d H:i:s")."] : User Account was not found\n", 3, "upload-errors.log" ); 
		//saveError("UserUpload", NULL, date("Y-m-d H:i:s"), "User Account was not found");  		
		exit;
	}
	
// Save Image To FTP
	$FileName = UploadFile( (string) $nMediaID, $Image[4] );
// Get New Media Data for response
	
	echo '
<Media ID="'.$nMediaID.'" BeMediaID="be'.$nMediaID.'">
	<Text ID="'.$nTextID.'"/>
	<Image ID="'.$nImageID.'" FileName="'.$FileName.'"/>
</Media>';

function UploadFile( $Dir, $FileName)
{
	if ($_FILES["file"]["error"] > 0)
	{
		echo '<Error Message="'.$_FILES["file"]["error"].'" Domain="UserUpload" />';
				error_log( "[".date("Y-m-d H:i:s")."] : ".$_FILES["file"]["error"]."\n", 3, "upload-errors.log" );  
		//saveError("UserUpload", NULL, date("Y-m-d H:i:s"), $_FILES["file"]["error"]);  		
		exit;
	}
	else
	{
//		echo "file name: " . $_FILES["file"]["name"]."<br/>";
//		echo "file type: " . $_FILES["file"]["type"]."<br/>";
//		echo "file size: " . ($_FILES["file"]["size"] / 1024)." Kb<br />";
//		echo "tmp file name: " . $_FILES["file"]["tmp_name"];		
		if (!is_uploaded_file($_FILES['file']['tmp_name']))
		{
			echo '<Error Message="Temp file not uploaded." Domain="UserUpload" />';
				error_log( "[".date("Y-m-d H:i:s")."] : Temp file not uploaded.\n", 3, "upload-errors.log" ); 
			//saveError("UserUpload", NULL, date("Y-m-d H:i:s"), "Temp file not uploaded.");  		
			
			exit;
		}
//		if ($_FILES['file']['size']> 300000)     //Limiting image at 300K
//		{
//			echo "<Error Message=\"Your file is too large.\" Domain=\"UserUpload\" />";
//			exit;
//		}
		if( !is_dir("C:\\wamp\\www\\media_storage\\".$Dir) )
			mkdir("C:\\wamp\\www\\media_storage\\".$Dir);
		move_uploaded_file($_FILES["file"]["tmp_name"],
						"C:\\wamp\\www\\media_storage\\".$Dir."\\".$FileName);
//		echo "tmp file name: " . $_FILES["file"]["tmp_name"];
	}
	
//	$uploaddir = '';      //Uploading to same directory as PHP file
//	$file = basename($_FILES['userfile']['name']);
//	$uploadfile = $uploaddir . $file;
	$strSqlCommand = "SELECT MediaDownloadPath FROM Global_Config WHERE 1";
	$result = mysql_query($strSqlCommand);
	$row = @mysql_fetch_array($result);	
	$ServerPath = $row['MediaDownloadPath'];

	return $ServerPath.$Dir."/".$FileName;
}
?>